﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using hStatsC.Helper;
using hStatsC.Views;
using Panuon.UI.Silver;
using PropertyChanged;

namespace hStatsC
{
    [AddINotifyPropertyChangedInterface]
    public partial class DashboardView : WindowX
    {
        public int Viewcount { get; set; } = 0;

        public DashboardView()
        {
            InitializeComponent();
            try
            {
                MainHelper.GetAppInfos();
            }
            catch (Exception exception)
            {
                MessageBoxX.Show("获取用户App信息出现了异常!");
            }

            this.DataContext = this;
        }

        private void Btn_ChangeView(object sender, RoutedEventArgs e)
        {
            Viewcount = int.Parse(((RadioButton) sender)?.Tag?.ToString()!);
        }

        private async void DashboardView_OnLoaded(object sender, RoutedEventArgs e)
        {
            await Task.Delay(2000);
            CheckUpdate();
        }

        private void CheckUpdate(bool showNoUpdate = false)
        {
            if (App.hCore.CheckUpdate(out var version))
            {
                var r = MessageBoxX.Show(
                    $"hStatsC发现新版本!\n" +
                    $"最新版本{version.Version}\n" +
                    $"版本发布时间\n{version.UpdateTime}\n" +
                    $"版本更新日志\n{version.UpdateLog}\n" +
                    $"{(version.DownloadLink.StartsWith("http") ? "点击确定跳转至下载链接" : "")}",
                    "版本更新");
                if (r == MessageBoxResult.OK && version.DownloadLink.StartsWith("http"))
                {
                    Process.Start("explorer.exe", version.DownloadLink);
                }
            }
            else
            {
                if (showNoUpdate)
                {
                    MessageBoxX.Show(
                        $"hStatsC已是最新版本\n" +
                        $"最新版本{version.Version}\n" +
                        $"版本发布时间\n{version.UpdateTime}\n" +
                        $"版本更新日志\n{version.UpdateLog}\n"
                        ,
                        "版本更新");
                }
            }
        }

        private void Btn_APIDoc(object sender, RoutedEventArgs e)
        {
            Process.Start("explorer.exe", "http://api.heerdev.top:4999/");
        }

        private void Btn_Update(object sender, RoutedEventArgs e)
        {
            CheckUpdate( true);
        }
    }
}